import 'package:flutter/material.dart';
import '../view/category_top_view.dart';
import '../../services/class_info_manger.dart';
import '../../models/class_info_model.dart';
import '../../manger/cached_image_widget.dart';
import '../../home/homeController/search_page.dart';
import '../controller/product_detail.dart';
import '../../manger/qysdk_manger.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';

class CategoryPage extends StatefulWidget {
  const CategoryPage({super.key});

  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  late Future<List<ClassListInfoModel>> _futureData;
  int selectIndex = 0; // 选中的索引

  @override
  void initState() {
    super.initState();
    _futureData = _loadData();
  }

  Future<List<ClassListInfoModel>> _loadData() async {
    final manager = ClassInfoManager();
    final success = await manager.loadInfoData();
    if (success.success) {
      setState(() {});
      return manager.classInfoModel ?? [];
    } else {
      throw Exception('加载失败');
    }
  }

  // 静默刷新数据
  Future<void> _refreshData() async {
    final manager = ClassInfoManager();
    final success = await manager.loadInfoData();
    if (success.success) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // 顶部搜索栏
          SizedBox(
            height: 155,
            child: Container(
              color: Colors.transparent,
              child: CategoryTopView(
                onSearchAction: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => const SearchPage()),
                    );
                },
                onContact: () {
                  QYSDK.showQYSession();  
                },
              ),
            ),
          ),
          // 主内容
          Expanded(
            child: FutureBuilder<List<ClassListInfoModel>>(
              future: _futureData,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                } else if (snapshot.hasError) {
                  return Center(child: Text('加载失败: ${snapshot.error}'));
                } else if (!snapshot.hasData || snapshot.data == null) {
                  return const Center(child: Text('暂无数据'));
                } else {
                  final List<ClassListInfoModel> data = snapshot.data!;

                  // 静默刷新按钮，模拟刷新数据
                  return RefreshIndicator(
                    onRefresh: _refreshData,
                    child: Row(
                      children: [
                        // 左侧分类列表
                        SizedBox(
                          width: 100,
                          child: ListView.builder(
                            padding: EdgeInsets.zero, // 移除默认的 padding
                            itemCount: data.length,
                            itemBuilder: (context, index) {
                              return CategoryItem(
                                title: data[index].name,
                                isSelected: index == selectIndex,
                                onTap: () {
                                  setState(() {
                                    selectIndex = index;
                                  });
                                },
                              );
                            },
                          ),
                        ),
                        // 右侧内容网格
                        Expanded(
                          child: Container(
                            color: Colors.white, // 设置背景色为白色
                            child: Padding(
                              padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 20),
                              child: GridView.builder(     
                                padding: EdgeInsets.only(top: 10, bottom: 10),                  
                                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 3,
                                  crossAxisSpacing: 15,
                                  mainAxisSpacing: 15,
                                  childAspectRatio:  isChineseLocale() ? 0.83 : 0.75,
                                ),
                                itemCount: data[selectIndex].childrenList.length,
                                itemBuilder: (context, index) {
                                  var item = data[selectIndex].childrenList[index];
                                  return ContentItem(
                                    title: item.name,
                                    imageUrl: item.imgUrl,
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => ProductDetailPage(
                                            categoryId: item.categoryId,
                                          ),
                                        ),
                                      );
                                    },
                                  );
                                },
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                }
              },
            ),
          ),
        ],
      ),
    );
  }
}

class CategoryItem extends StatelessWidget {
  final String title;
  final bool isSelected;
  final VoidCallback onTap;

  const CategoryItem({
    Key? key,
    required this.title,
    required this.isSelected,
    required this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 50,
        color: isSelected ? Colors.white : Colors.transparent,
        child: Row(
          children: [
            // 左侧线条
            Container(
              width: 2,
              color: isSelected ? Color(0xFF5D5FEE) : Colors.transparent,
            ),
            // 右侧文本
            Expanded(
              child: Center(
                child: Text(
                  title,
                  textAlign: TextAlign.center, // 显式设置居中
                  style: TextStyle(
                    fontSize: 15,
                    color: isSelected ? Color(0xFF5D5FEE) : Color(0xFF666666),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class ContentItem extends StatelessWidget {
  final String title;
  final String imageUrl;
  final VoidCallback onTap;

  const ContentItem({
    Key? key,
    required this.title,
    required this.imageUrl,
    required this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          // 图片
          ClipRRect(
            borderRadius: BorderRadius.circular(10),
              child: CachedImage(
                width: 58,  // 固定宽度为 50
                height: 58,  // 固定高度为 50
                imageUrl: imageUrl,
                fit: BoxFit.cover,
                placeholderPath: 'assets/images/placeholderImage.png',  // 占位符图片路径 

              ),
        
          ),
          const SizedBox(height: 8),
          // 文字
          SizedBox(
            width: 68,
            child: Text(
              title,
              textAlign: TextAlign.center,
              style: const TextStyle(
                fontSize: 13, 
                color: Colors.black,
                height: 0.9,
              ),
              maxLines: isChineseLocale() ? 1 : 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }
}
